// +----------------------------------------------------------------------
// | CmsWing [ 美业管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 psi All rights reserved.
// +----------------------------------------------------------------------
// | Author: huang <2374266244@qq.com>
// +----------------------------------------------------------------------
'use strict';
import Base from './base.js';

/**
*开单页面控制器
*/
export default class extends Base {

	async orderlistAction(){
		let filter = JSON.parse(this.get('filter'))
		let where = {
			'o.departmentid': this.shop_userinfo.departmentid,
			'o.ordertype': 2,
			's.name|s.vipcard|s.phone|a.name|oa.name|o.order_sn': ['like', '%' + filter.search + '%']
		}
		if (filter.status != 0) {
			where['o.status'] = filter.status - 1
		}

		if (filter.times && (filter.times[0] != null && filter.times[1] != null)) {
			let begintime = Math.floor(new Date(filter.times[0]).setHours(0,0,0,0)/1000)
			let endtime = Math.floor(new Date(filter.times[1]).setHours(0,0,0,0)/1000) + 86400
			where['o.addtime'] = {'>=': begintime, '<': endtime}
 		}
	
		let list = await this.model('or_shop_order')
		.alias('o')
		.field('o.id, d.name as shopname, s.name as gname,s.phone as gphone,s.vipcard,o.order_sn,o.consumemoney,o.recemoney,o.usebalance,o.usegiftbalance,o.addtime,o.operatorid,o.auditorid,o.status, a.name as operatorname, oa.name as auditorname, o.cardreduce, o.guestid')
		.join('`think_or_guest` s on s.id = o.guestid')
		.join('`think_or_department` d on s.departmentid = d.id')
		.join('`think_or_admin` a on a.id = o.operatorid')
		.join('`think_or_admin` oa on oa.id = o.auditorid')
		.where(where)
		.page(filter.currentSize, filter.pageSize)
		.order('o.addtime desc')
		.countSelect()

		return this.json(list)

	}

	/**
	* 开单
	* @author 黄
	*/
	async openorderAction(){
		let data = JSON.parse(this.post('data'))

		//订单表数据
		let orderdata = {
			order_sn			: await this.getordersn('LSD',1),
			guestid				: data.uinfo.id,
			departmentid 	: this.shop_userinfo.departmentid,
			consumemoney 	: data.consumemoney,
			recemoney			: 0,
			cardreduce			: 0,
			operatorid		: this.shop_userinfo.id,
			addtime				: Math.round(Date.parse(new Date())/1000),
			remarks: data.remarks,
			ordertype			: 2
		}

		// 有两种方案，第一种是先写进订单表结账时计算和判断库存并添加暂存，第二种是写表的同时计算判断库存并添加暂存
		// 先用第一种方案
		let model = this.model('or_shop_order');
		await model.transaction(async()=>{
			try{
				// 要写入的表有，order，orderinfo，有暂存写到暂存表
				let resorder = await model.add(orderdata);
				let orderinfodata = []
				data.tableData.forEach((row) => {
					orderinfodata.push({
						departmentid: this.shop_userinfo.departmentid,
						orderid: resorder,
						consumetype: row.consumetype,
						type: row.goodstype,
						typeid: row.id,
						typename: row.name,
						guestcardid: row.cardid ? row.cardid : 0,
						guestcardinfoid: row.guestcardinfoid ? row.guestcardinfoid : 0,
						num: row.num,
						price: row.price,
						totalprice: (row.price * row.num).toFixed(2),
						discount: row.discount,
						amount: row.amount,
						istemp: row.issave ? 1 : 0,
						isgift: row.isgift ? 1 : 0,
						brandid: row.brandid,
						tempid: row.savesid ? row.savesid : 0
					})
				})

				let resorderinfo = await this.model('or_shop_orderinfo').db(model.db()).addMany(orderinfodata);

				if (resorder && resorderinfo) {
					await model.commit();
					return this.success({data:200, info:'开单成功'});
				} else {
					await model.rollback();
					return this.fail("开单失败！");
				}
			}catch(e){
				console.log(e)
				await model.rollback();
				return this.fail("开单失败！");
			}
		})
	}


	/*
	 * 新开单把散客和老客合并在一起方便后期维护
	 * @author: huang
	 */
	
	async newopenorderAction () {
		let data = JSON.parse(this.post('data'))

		//先查看订单是否已经被删除或者已经结账
		if (data.order.id) {
			let order = await this.model('or_shop_order').where({id: data.order.id}).find()
			if (!order || order.status != 0) {
				return this.fail('该订单不存在或者已经结账！')
			}
		}
		// 制作订单数据表
		let orderdata = {
			order_sn: data.order.order_sn ? data.order.order_sn : await this.getordersn('LSD', 1),
			guestid: data.ginfo.id,
			departmentid: this.shop_userinfo.departmentid,
			operatorid: this.shop_userinfo.id,
			addtime: Math.round(Date.parse(new Date())/1000),
			remarks: data.order.remarks,
			recemoney: data.order.usemoney,
			cardreduce: data.order.usecard,
			usebalance: data.order.usebalance,
			usegiftbalance: data.order.usegiftbalance,
			ordertype: 2,
			iscross: data.order.crossShop
		}

		let model = this.model('or_shop_order')
		await model.transaction(async()=>{
			try{
				// 要写入的表有，order，orderinfo，有暂存写到暂存表
				let resorder = 1
				if (data.order.id) {
					resorder = await model.where({id: data.order.id}).update(orderdata)
				} else {
					resorder = await model.add(orderdata)
				}

				let orderinfodata = []
				data.orderlist.forEach((row) => {
					orderinfodata.push({
						departmentid: this.shop_userinfo.departmentid,
						orderid: data.order.id ? data.order.id : resorder,
						consumetype: row.consumetype,
						type: row.type,
						typeid: row.typeid,
						typename: row.typename,
						guestcardid: row.guestcardid ? row.guestcardid : 0,
						guestcardinfoid: row.guestcardinfoid ? row.guestcardinfoid : 0,
						num: row.num,
						price: row.price,
						totalprice: (row.price * row.num).toFixed(2),
						discount: row.discount,
						amount: row.amount,
						usemoney: row.usemoney,
						usebalance: row.usebalance,
						usegiftbalance: row.usegiftbalance,
						usecard: row.usecard,
						istemp: row.istemp ? 1 : 0,
						isgift: row.isgift ? 1 : 0,
						brandid: row.brandid,
						tempid: row.tempid ? row.tempid : 0
					})
				})
				let resdelorderinfo = 1
				if (data.order.id) {
					let resdelorderinfo = await this.model('or_shop_orderinfo').db(model.db()).where({orderid: data.order.id}).delete(); // 删除老数据
				}
				// 更新客户备注（这个暂时不放在回滚里面删除订单时无法退回）
				if (data.ginfo.id != 1 && data.ginfo.id != 2) {
					let resguest = await this.model('or_guest').db(model.db()).where({id: data.ginfo.id}).update({remarks: data.ginfo.remarks})
				}

				let resorderinfo = await this.model('or_shop_orderinfo').db(model.db()).addMany(orderinfodata);

				if (resorder && resorderinfo && resdelorderinfo) {
					await model.commit();
					return this.success({id: data.order.id ? data.order.id : resorder, info:'操作成功！'});
				} else {
					await model.rollback();
					return this.fail("操作失败！");
				}
			}catch(e){
				console.log(e)
				await model.rollback();
				return this.fail("操作失败！");
			}
		})
	}

	/**
	* @auth：fzg
	* 时间：2017/09/29
	* 功能：散客开单(仿照会员开单)
	*/
	async opendisperorderAction(){
		let data = JSON.parse(this.post('data'))

		//订单表数据
		let orderdata = {
			order_sn			: await this.getordersn('LSD',1),
			guestid				: data.uinfo.id,
			departmentid 	: this.shop_userinfo.departmentid,
			consumemoney 	: data.consumemoney,
			recemoney			: 0,
			cardreduce			: 0,
			operatorid		: this.shop_userinfo.id,
			addtime				: Math.round(Date.parse(new Date())/1000),
			remarks: data.remarks,
			ordertype			: 2
		}

		// 有两种方案，第一种是先写进订单表结账时计算和判断库存并添加暂存，第二种是写表的同时计算判断库存并添加暂存
		// 先用第一种方案
		let model = this.model('or_shop_order');
		await model.transaction(async()=>{
			try{
				// 要写入的表有，order，orderinfo，有暂存写到暂存表
				let resorder = await model.add(orderdata);
				let orderinfodata = []
				data.tableData.forEach((row) => {
					orderinfodata.push({
						departmentid: this.shop_userinfo.departmentid,
						orderid: resorder,
						consumetype: row.consumetype,
						type: row.goodstype,
						typeid: row.id,			//???
						typename: row.name,
						guestcardid: 0,
						guestcardinfoid: 0,
						num: row.num,
						price: row.price,
						totalprice: (row.price * row.num).toFixed(2),
						discount: row.discount,
						amount: row.amount,
						istemp: 0,
						isgift: row.isgift ? 1 : 0,
						brandid: row.brandid,
						tempid: 0
					})
				})

				let resorderinfo = await this.model('or_shop_orderinfo').db(model.db()).addMany(orderinfodata);

				if (resorder && resorderinfo) {
					await model.commit();
					return this.success({data:200, info:'开单成功'});
				} else {
					await model.rollback();
					return this.fail("开单失败！");
				}
			}catch(e){
				console.log(e)
				await model.rollback();
				return this.fail("开单失败！");
			}
		})
	}

	/**
	* 删除订单
	* @author：黄
	*/
	async deleteorderAction(){
		let id = this.post('id');

		// 判断是否可以删除
		let order = await this.model('or_shop_order').where({id: id}).find()
		if (!order || order.status != 0) {
			return this.fail('该订单不存在或者已经结账！')
		}
		//删除操作
		let model = this.model('or_shop_order');
		await model.transaction(async()=>{
			try{
				let ores = await model.where({id:id}).delete();
				let gres = await this.model('or_shop_orderinfo').db(model.db()).where({orderid:id}).delete();
				if (ores && gres) {
					await model.commit();
					return this.success({data:200, info:'删除成功！'});
				} else {
					await model.rollback();
					return this.fail("删除失败！");
				}
			}catch(e){
				console.log(e);
				await model.rollback();
				return this.fail("删除失败！");
			}
		});
	}

	/**
	* 付款结账功能
	* @author：黄
	*/
	async jiezhangAction(){
		// 获取需要的数据
		let data = JSON.parse(this.post('data'))
		let orderinfo = await this.model('or_shop_order').where({id:data.order.id}).find()
		let nowtime = orderinfo.addtime
		let orderlist = await this.model('or_shop_orderinfo')
				.alias('o')
				.field('o.*, s.nownum, t.nownum as tnownum, s.isdisabled, t.isdisabled as goodsdisabled')
				.join('left join `think_or_shop_guestcardsubject` s on o.guestcardinfoid = s.id')
				.join('left join `think_or_shop_guest_temp_reserve` t on o.tempid = t.id')
				.where({'o.orderid': data.order.id})
				.select()
		let shop_id = this.shop_userinfo.departmentid

		/**
		*过账前的判断
		*判断是否结账  前置
		*判断商品库存是否足够 后置
		*判断用户卡项是否足够充值卡判断余额、期卡判断日期、次卡判断次数 后置
		*判断暂存商品或项目是否存在 后置
		*判断银行卡是否可用 后置
		*判断账户余额和赠送金额是否足够 后置
		*/

		// 判断当前订单是否已经结账
		if (orderinfo.status == 1) {
			return this.fail('订单已结账');
		}

		// 事务开启
		let guestModel = this.model('or_shop_order');
		await guestModel.transaction(async()=>{
			try{
				let resxianjin = 1, resorder = 1, resreduce = 1, resyeji = 1;
				// 现金业绩表
				// 重新规划业绩分配，暂时用两种方式
				if (data.yejilist.length > 0) {
					let yejidata = [], selluserList = [], reduceuserList = []
					data.yejilist.forEach((row) => {
						yejidata.push({
							shopid: shop_id,
							orderid: data.order.id,
							ordertype: 'LSD',
							xianjinyeji: row.xianjinyeji,
							kahaoyeji: row.kahaoyeji,
							userid: row.userid,
							bumenid: row.bumenid,
							xiaozuid: row.xiaozuid,
							guestid: data.order.guestid,
							fuwutype: row.fuwutype,
							addtime: nowtime
						})
						if (row.xianjinyeji > 0) {
							selluserList.push({
								orderid 	: data.order.id,
								feattype	: 'LSD',
								shopid 		: shop_id,
								feat 		: row.xianjinyeji,
								userid 		: row.userid,
								bumenid 	: row.bumenid,
								xiaozuid 	: row.xiaozuid,
								guestid     : data.order.guestid,
								addtime 	: nowtime
							})
						}
						if (row.kahaoyeji > 0) {
							reduceuserList.push({
								orderid 	: data.order.id,
								feattype	: 'LSD',
								shopid 		: shop_id,
								feat 		: row.kahaoyeji,
								userid 		: row.userid,
								bumenid 	: row.bumenid,
								xiaozuid 	: row.xiaozuid,
								guestid     : data.order.guestid,
								addtime 	: nowtime
							})
						}
					})

					if (selluserList.length > 0) {
						resxianjin = await this.model('or_shop_yejixianjin').db(guestModel.db()).addMany(selluserList);
					}
					if (reduceuserList.length > 0) {
						resreduce = await this.model('or_shop_yejicardreduce').db(guestModel.db()).addMany(reduceuserList);
					}
					resyeji = await this.model('or_shop_yejiticheng').db(guestModel.db()).addMany(yejidata)
				}
				

				let orderdata = {
					status : 1,
					auditorid : this.shop_userinfo.id,
					gendanid: data.order.gendanid
				}

				
				// 更改操作客户的余额和写入账户金额
				// 判断是否使用客户的余额，如果使用更改客户的余额信息，并且写入客户余额变动日志

				let ginfo = await this.model('or_guest').db(guestModel.db()).where({id: data.order.guestid}).find()
				let ginfodata = {arrivetime: nowtime}, ginfodatalog = {}, accountdata = [], accountdatalog = []
				if (data.order.usebalance > 0 || data.order.usegiftbalance > 0) {
					if (ginfo.giftbalance - data.order.usegiftbalance < 0) {
						await guestModel.rollback()
						return this.fail('该客户赠送余额不足以支付当前订单！')
					}
					ginfodata = Object.assign(ginfodata, {balance: ginfo.balance - data.order.usebalance, giftbalance: ginfo.giftbalance - data.order.usegiftbalance})
					ginfodatalog = {
						guestid: data.order.guestid,
						shopid: shop_id,
						ordertype: 'LSD',
						orderid: data.order.id,
						balance: -1 * data.order.usebalance,
						giftbalance: -1 * data.order.usegiftbalance,
						addtime: nowtime,
						type: 3
					}
				}
				for (var i = data.paylist.length - 1; i >= 0; i--) {
					// 普通收款
					if (data.paylist[i].type == 1) {
						let account = await this.model('or_shop_account').db(guestModel.db()).where({id: data.paylist[i].accountid}).find()
						account.balance += Number(data.paylist[i].paymoney)
						accountdata.push(account)
						accountdatalog.push({
							departmentid: shop_id,
							accountid: data.paylist[i].accountid,
							ordertype: 'LSD',
							type: 1,
							orderid: data.order.id,
							money: data.paylist[i].paymoney,
							addtime: nowtime
						})
					}
				};

				let resginfo = 1, resginfolog = 1, resaccount = 1, resaccountlog = 1
				resginfo = await this.model('or_guest').db(guestModel.db()).where({id: data.order.guestid}).update(ginfodata)
				if (!think.isEmpty(ginfodatalog)) {
					resginfolog = await this.model('or_shop_guest_accountlog').db(guestModel.db()).add(ginfodatalog)
				}

				if (accountdata.length > 0) {
					resaccount = await this.model('or_shop_account').db(guestModel.db()).updateMany(accountdata)
					resaccountlog = await this.model('or_shop_accountlog').db(guestModel.db()).addMany(accountdatalog)
				}

				// 开始判断客户卡项信息并且减去相应的卡信息
				let goodsdata = [],goodsdatalog = [], cikadata = [], kaxiangdatalog = [], zancundata = [], zancunadddata = []
				for (var i = orderlist.length - 1; i >= 0; i--) {
					// 现金支付判断商品库存是否足够（先不做）先减去库存
					// 客户暂存的话库存也直接减掉，因为改产品已经属于客户，不能再出售
					if (orderlist[i].consumetype == 1) {
						// 操作库存
						if (orderlist[i].type == 1) {
							// 产品
							let goods = await this.model('or_shop_goods').db(guestModel.db()).where({goodsid: orderlist[i].typeid, shopid: shop_id}).find()
							goods.nums -= Number(orderlist[i].num)
							goodsdata.push(goods)
							goodsdatalog.push({
								departmentid: shop_id,
								goodsid: orderlist[i].typeid,
								ordertype: 'LSD',
								orderid: data.order.id,
								nums: -1 * orderlist[i].num,
								addtime: orderinfo.addtime,
								posttime: nowtime
							})
						}
						// 如果有暂存商品或项目加入到暂存表中去
						if (orderlist[i].istemp == 1) {
							zancunadddata.push({
								orderid: data.order.id,
								shopid: shop_id,
								guestid: data.order.guestid,
								goodsid: orderlist[i].typeid,
								price: orderlist[i].price,
								num: orderlist[i].num,
								nownum: orderlist[i].num,
								disprice: orderlist[i].price * orderlist[i].discount,
								amount: orderlist[i].amount,					
								addtime: nowtime,
								brandid: orderlist[i].brandid,
								isgift: orderlist[i].isgift,
								isdisabled: 0							
							})
						}
					}
					

					// 判断是否有卡信息
					if (orderlist[i].consumetype == 2) {
						// 期卡
						if (orderlist[i].cardtype == 1 && orderlist[i].endtime < nowtime) {
							await guestModel.rollback()
							return this.fail('客户期卡已经到期！不能结账！')					
						}
						// 次卡
						if (orderlist[i].cardtype == 2 && orderlist[i].num > orderlist[i].nownum) {
							await guestModel.rollback()
							return this.fail('客户次卡剩余数量不足！不能结账！')	
						}
						if (orderlist[i].isdisabled == 1) {
							await guestModel.rollback()
							return this.fail('有卡项已经失效！不能结账！')
						}
						let k = await this.model('or_shop_guestcardsubject').db(guestModel.db()).where({id: orderlist[i].guestcardinfoid}).find()
						k.nownum -= Number(orderlist[i].num)
						k.amount -= orderlist[i].amount
						k.amount = k.amount < 0 ? 0 : k.amount
						cikadata.push(k)

						// 后期应该改成统一表，期卡里应加入消费次数
						kaxiangdatalog.push({
							departmentid: shop_id,
							guestcardid: orderlist[i].guestcardid,
							guestcardinfoid: orderlist[i].guestcardinfoid,
							num: -1 * orderlist[i].num,
							amount: -1 * orderlist[i].amount,
							addtime: nowtime,
							orderid: data.order.id,
							ordertype: 'LSD'
						})
					}

					// 操作暂存信息
					if (orderlist[i].consumetype == 3) {
						// 判断客户暂存数量是否足够（nownum问题）
						if (orderlist[i].num > orderlist[i].tnownum) {
							await guestModel.rollback()
							return this.fail('客户暂存商品剩余数量不足！不能结账！')
						}
						if (orderlist[i].goodsdisabled == 1) {
							await guestModel.rollback()
							return this.fail('该产品已经失效！不能结账！')
						}
						let z = await this.model('or_shop_guest_temp_reserve').db(guestModel.db()).where({id: orderlist[i].tempid}).find()
						z.nownum -= Number(orderlist[i].num)
						zancundata.push(z)
					}
				};

				let resgoods = 1, resgoodslog = 1, rescika = 1, reskaxianglog = 1, reszancun = 1, resaddzancun = 1

				if (zancunadddata.length > 0) {
					resaddzancun = await this.model('or_shop_guest_temp_reserve').db(guestModel.db()).addMany(zancunadddata)
				}

				if (goodsdata.length > 0) {
					resgoods = await this.model('or_shop_goods').db(guestModel.db()).updateMany(goodsdata)
					resgoodslog = await this.model('or_shop_goodslog').db(guestModel.db()).addMany(goodsdatalog)
				}

				if (cikadata.length > 0) {
					rescika = await this.model('or_shop_guestcardsubject').db(guestModel.db()).updateMany(cikadata)
				}

				if (kaxiangdatalog.length > 0) {
					reskaxianglog = await this.model('or_shop_guestcardlog').db(guestModel.db()).addMany(kaxiangdatalog)
				}

				if (zancundata.length > 0) {
					reszancun = await this.model('or_shop_guest_temp_reserve').db(guestModel.db()).updateMany(zancundata)
				}
				
				// 更改订单状态为1表示订单已结账
				resorder =  await guestModel.where({id: data.order.id}).update(orderdata)

				//完善预约（保留）
				//获取今天时间戳范围
				let date = new Date();
				let btoday = Math.round(new Date(date.getFullYear(),date.getMonth(),date.getDate(),0,0,0).getTime()/1000);
				let etoday = btoday+86400;
				let resyuyue = await this.model('bespeak').db(guestModel.db()).execute('UPDATE `think_bespeak` SET `type`=2,`arrivetime`='+nowtime+' WHERE  `guestid` = '+data.order.guestid+' and bespeaktime >= '+btoday+' and bespeaktime < '+etoday)
				/*console.log(resxianjin)
				console.log(resxiaohao)
				console.log(resorder)
				console.log(resreduce)
				console.log(resginfo)
				console.log(resginfolog)
				console.log(resaccount)
				console.log(resaccountlog)
				console.log(resgoods)
				console.log(resgoodslog)
				console.log(rescika)
				console.log(reskaxianglog)
				console.log(reszancun)
				console.log(resyuyue)*/
				if (resyeji && resxianjin && resorder && resreduce && resginfo && resginfolog && resaccount && resaccountlog && resgoods && resgoodslog && rescika && reskaxianglog && reszancun && resaddzancun) {
					await guestModel.commit();
					return this.success({data:200, info:'结账成功'});
				} else {
					await guestModel.rollback();
					return this.fail('结账失败');
				}

			}catch(e){
				
				await guestModel.rollback();
				console.log(e)
				return this.fail('结账失败');
			}
		})
	}

	/**
	* 获取订单详细信息
	* @author：黄
	*/
	async getorderinfoAction () {
		let orderid = this.post('orderid')
		let orderinfo = await this.model('or_shop_order').where({id: orderid}).find()
		if (orderinfo.gendanid) {
			orderinfo.gendanname = await this.model('or_app_user').where({id: orderinfo.gendanid}).getField('name', true)
		}
		let orderlist = await this.model('or_shop_orderinfo')
		.alias('o')
		.field('o.*, c.name as cardname, if(o.tempid != 0, gr.nownum, gs.nownum) as nownum, gs.cardtype')
		.join('left join `think_or_shop_card` c on o.guestcardid = c.id')
		.join('left join `think_or_shop_guestcardsubject` gs on o.guestcardinfoid = gs.id')
		.join('left join `think_or_shop_guest_temp_reserve` gr on o.tempid = gr.id')
		.where({'o.orderid': orderid})
		.select()
		
		let ginfo = await this.model('or_guest')
		.alias('g')
		.field('g.*, v.vipname, v.goodsdiscount, v.subjectdiscount')
		.join('left join `think_or_guest_vipgrade` v on g.level = v.id')
		.where({'g.id': orderinfo.guestid})
		.find()	

		// 获取结账和分配信息
		let accountlist = await this.model('or_shop_accountlog')
		.alias('al')
		.join('left join `think_or_shop_account` a on al.accountid = a.id')
		.where({orderid: orderid, ordertype: 'LSD'})
		.select()
		
		let alist = []
		// 组合成订单表的信息
		if (accountlist.length > 0) {
			accountlist.forEach((row) => {
				alist.push({
					id: row.accountid,
					type: 1,
					accountname: row.name,
					paymoney: row.money
				})
			})
		}
		

		// 业绩分配
		let yejilist = await this.model('or_shop_yejiticheng')
		.alias('y')
		.field('y.*, u.name,u.username')
		.join('left join `think_or_app_user` u on y.userid = u.id')
		.where({'y.ordertype': 'LSD', 'y.orderid': orderid, 'y.addtype': 0})
		.select()

		let data = {
			orderinfo: orderinfo,
			orderlist: orderlist,
			ginfo: ginfo,
			alist: alist,
			yejilist: yejilist
		}
		return this.json(data)
	}

	/**
	* 编辑订单
	* @author：黄
	*/
	async editorderAction () {
		let data = JSON.parse(this.post('data'))
		//先查看订单是否已经被删除或者已经结账
		let order = await this.model('or_shop_order').where({id: data.id}).find()
		if (!order || order.status != 0) {
			return this.fail('该订单不存在或者已经结账！')
		}

		//订单表数据
		let orderdata = {
			guestid				: data.uinfo.id,
			consumemoney 	: data.consumemoney,
			recemoney			: 0,
			cardreduce			: 0,
			operatorid		: this.shop_userinfo.id,
			remarks: data.remarks,
			ordertype			: 2
		}

		// 有两种方案，第一种是先写进订单表结账时计算和判断库存并添加暂存，第二种是写表的同时计算判断库存并添加暂存
		// 先用第一种方案
		let model = this.model('or_shop_order');
		await model.transaction(async()=>{
			try{
				// 要写入的表有，order，orderinfo
				let resorder = await model.where({id: data.id}).update(orderdata); // 更新
				let orderinfodata = []
				data.tableData.forEach((row) => {
					orderinfodata.push({
						departmentid: this.shop_userinfo.departmentid,
						orderid: data.id,
						consumetype: row.consumetype,
						type: row.type,
						typeid: row.typeid,
						typename: row.name,
						guestcardid: row.cardid ? row.cardid : 0,
						guestcardinfoid: row.guestcardinfoid ? row.guestcardinfoid : 0,
						num: row.num,
						price: row.price,
						totalprice: (row.price * row.num).toFixed(2),
						discount: row.discount,
						amount: row.amount,
						istemp: row.istemp ? 1 : 0,
						isgift: row.isgift ? 1 : 0,
						brandid: row.brandid,
						tempid: row.savesid ? row.savesid : 0
					})
				})
				/*console.log(orderdata)
				console.log(orderinfodata)
				console.log(tempdata)*/

				let resdelorderinfo = await this.model('or_shop_orderinfo').db(model.db()).where({orderid: data.id}).delete(); // 删除老数据
				let resorderinfo = await this.model('or_shop_orderinfo').db(model.db()).addMany(orderinfodata); // 写入新数据

				if (resorder && resorderinfo && resdelorderinfo) {
					await model.commit();
					return this.success({data:200, info:'编辑成功'});
				} else {
					await model.rollback();
					return this.fail("编辑失败！");
				}
			}catch(e){
				console.log(e)
				await model.rollback();
				return this.fail("编辑失败！");
			}
		}) 
	}

	/**
	* @author:fzg
	* 时间：2017/09/30
	* 功能：散客订单编辑(仿照客户订单编辑)
	*/
	async editdisperorderAction () {
		let data = JSON.parse(this.post('data'))

		//先查看订单是否已经被删除或者已经结账
		let order = await this.model('or_shop_order').where({id: data.id}).find()

		if (!order || order.status != 0) {
			return this.fail('该订单不存在或者已经结账！')
		}

		//订单表数据
		let orderdata = {
			guestid				: data.uinfo.id,
			consumemoney 	: data.consumemoney,
			recemoney			: 0,
			cardreduce			: 0,
			operatorid		: this.shop_userinfo.id,
			addtime				: Math.round(Date.parse(new Date())/1000),
			remarks: data.remarks,
			ordertype			: 2
		}

		// 有两种方案，第一种是先写进订单表结账时计算和判断库存并添加暂存，第二种是写表的同时计算判断库存并添加暂存
		// 先用第一种方案
		let model = this.model('or_shop_order');
		await model.transaction(async()=>{
			try{
				// 要写入的表有，order，orderinfo
				let resorder = await model.where({id: data.id}).update(orderdata); // 更新
				let orderinfodata = []
				data.tableData.forEach((row) => {
					orderinfodata.push({
						departmentid: this.shop_userinfo.departmentid,
						orderid: data.id,
						consumetype: row.consumetype,
						type: row.type,
						typeid: row.typeid,
						typename: row.name,
						guestcardid: 0,
						guestcardinfoid: 0,
						num: row.num,
						price: row.price,
						totalprice: (row.price * row.num).toFixed(2),
						discount: row.discount,
						amount: row.amount,
						istemp: 0,
						isgift: row.isgift ? 1 : 0,
						brandid: row.brandid
					})
				})
				/*console.log(orderdata)
				console.log(orderinfodata)
				console.log(tempdata)*/

				let resdelorderinfo = await this.model('or_shop_orderinfo').db(model.db()).where({orderid: data.id}).delete(); // 删除老数据
				let resorderinfo = await this.model('or_shop_orderinfo').db(model.db()).addMany(orderinfodata); // 写入新数据

				if (resorder && resorderinfo && resdelorderinfo) {
					await model.commit();
					return this.success({data:200, info:'编辑成功'});
				} else {
					await model.rollback();
					return this.fail("编辑失败！");
				}
			}catch(e){
				console.log(e)
				await model.rollback();
				return this.fail("编辑失败！");
			}
		}) 
	}

	/**
	* 更改业绩分配
	* @author：黄
	*/
	async edityejifenpeiAction () {
		let data = JSON.parse(this.post('data'))
		// 获取订单实时信息判断状态
		let order = await this.model('or_shop_order').where({id: data.order.id}).find()

		// 如果状态为3则不能更改业绩
		if (2 == order.status) {
			return this.fail('该订单已经审核不能再分配业绩！')
		}
		if (0 == order.status) {
			return this.fail('该订单尚未结账，不能分配业绩！')
		}
		// 删除已经分配好的业绩重新分配
		let model = this.model('or_shop_yejixianjin');
		await model.transaction(async()=>{
			try{
				
				let resyeji = 1, resxianjin = 1, resreduce = 1, resdelxianjin = 1, resdelreduce = 1, resdelyeji = 1;

				resdelxianjin = await model.where({orderid: data.order.id, feattype: 'LSD'}).delete()
				resdelreduce = await this.model('or_shop_yejicardreduce').db(model.db()).where({orderid: data.order.id, feattype: 'LSD'}).delete()
				resdelyeji = await this.model('or_shop_yejiticheng').db(model.db()).where({orderid: data.order.id, ordertype: 'LSD'}).delete()


				if (data.yejilist.length > 0) {
					let yejidata = [], selluserList = [], reduceuserList = []
					data.yejilist.forEach((row) => {
						yejidata.push({
							shopid: this.shop_userinfo.departmentid,
							orderid: data.order.id,
							ordertype: 'LSD',
							xianjinyeji: row.xianjinyeji,
							kahaoyeji: row.kahaoyeji,
							userid: row.userid,
							bumenid: row.bumenid,
							xiaozuid: row.xiaozuid,
							guestid: data.order.guestid,
							fuwutype: row.fuwutype,
							addtime: data.order.addtime
						})
						if (row.xianjinyeji > 0) {
							selluserList.push({
								orderid 	: data.order.id,
								feattype	: 'LSD',
								shopid 		: this.shop_userinfo.departmentid,
								feat 		: row.xianjinyeji,
								userid 		: row.userid,
								bumenid 	: row.bumenid,
								xiaozuid 	: row.xiaozuid,
								guestid     : data.order.guestid,
								addtime 	: data.order.addtime
							})
						}
						if (row.kahaoyeji > 0) {
							reduceuserList.push({
								orderid 	: data.order.id,
								feattype	: 'LSD',
								shopid 		: this.shop_userinfo.departmentid,
								feat 		: row.kahaoyeji,
								userid 		: row.userid,
								bumenid 	: row.bumenid,
								xiaozuid 	: row.xiaozuid,
								guestid     : data.order.guestid,
								addtime 	: data.order.addtime
							})
						}
					})

					if (selluserList.length > 0) {
						resxianjin = await this.model('or_shop_yejixianjin').db(model.db()).addMany(selluserList);
					}
					if (reduceuserList.length > 0) {
						resreduce = await this.model('or_shop_yejicardreduce').db(model.db()).addMany(reduceuserList);
					}
					resyeji = await this.model('or_shop_yejiticheng').db(model.db()).addMany(yejidata)
				}

				if (resyeji && resxianjin && resreduce && resdelxianjin !== false && resdelreduce !== false && resdelyeji) {
					await model.commit();
					return this.success({data:200, info:'编辑成功'});
				} else {
					await model.rollback();
					return this.fail("编辑失败！");
				}
			}catch(e){
				console.log(e)
				await model.rollback();
				return this.fail("编辑失败！");
			}
		})
	}

	async fanjiezhangAction () {
		let id = this.post('id')
		// 反结账要做哪些工作
		// 首先订单表状态要改变，其次业绩表要删除三张表都要删除
		// 有使用余额或者赠送余额的删除日志，返回金额
		// 有使用现金的返回金额，删除日志
		// 商品库存日志和记录
		// 删除暂存记录
		// 有使用次卡的返还次卡次数
		// 删除卡项纪录
		// 有使用暂存，返还暂存消费
		
		// 判断单据是否符合状态
		let oinfo = await this.model('or_shop_order')
		.where({id: id})
		.find()

		let olist = await this.model('or_shop_orderinfo').where({orderid: id}).select()

		if (oinfo.status != 1) {
			return this.fail('该订单已经分配或未结账')
		}
		// 如果

		// 事务开启
		let guestModel = this.model('or_shop_order');
		await guestModel.transaction(async()=>{
			try{
				let resxianjin = 1, resorder = 1, resreduce = 1;
				// 现金业绩表
				resxianjin = await this.model('or_shop_yejixianjin').db(guestModel.db()).where({orderid: id, feattype: 'LSD'}).delete();
				// 卡耗业绩
				resreduce = await this.model('or_shop_yejicardreduce').db(guestModel.db()).where({orderid: id, feattype: 'LSD'}).delete();

				let resyeji = await this.model('or_shop_yejiticheng').db(guestModel.db()).where({orderid: id, ordertype: 'LSD'}).delete()			
				
				let orderdata = {
					status : 0,
					auditorid : 0,
					gendanid: 0
				}
				let resdelbalancelog = 1, resbalance = 1
				// 判断是否使用余额
				if (oinfo.usebalance != 0 || oinfo.usegiftbalance != 0) {
					// 删除日志，返回金额
					resdelbalancelog = await this.model('or_shop_guest_accountlog').db(guestModel.db()).where({ordertype: 'LSD',orderid:id}).delete()
					// 取金额
					let ginfo = await this.model('or_guest').db(guestModel.db()).where({id: oinfo.guestid}).find()
					resbalance = await this.model('or_guest').db(guestModel.db()).where({id: oinfo.guestid}).update({
						balance: ginfo.balance + Number(oinfo.usebalance),
						giftbalance: ginfo.giftbalance + Number(oinfo.usegiftbalance)
					})
				}

				// 如果有普通收款，删除日志，返还金额
				let resaccount = 1, resaccountlog = 1
				if (oinfo.recemoney > 0) {
					let accountlog = await this.model('or_shop_accountlog').db(guestModel.db()).where({ordertype: 'LSD', orderid: id}).select()
					let accountdata = []
					for (var i = accountlog.length - 1; i >= 0; i--) {
						let account = await this.model('or_shop_account').db(guestModel.db()).where({id:accountlog[i].accountid}).find()
						account.balance -= Number(accountlog[i].money)
						accountdata.push(account)
					}
					resaccount = await this.model('or_shop_account').db(guestModel.db()).updateMany(accountdata)
					resaccountlog = await this.model('or_shop_accountlog').db(guestModel.db()).where({ordertype: 'LSD', orderid: id}).delete()
				}

				// 判断是否有商品
				let goodslog = await this.model('or_shop_goodslog').db(guestModel.db()).where({ordertype: 'LSD', orderid: id}).select()
				let resgoods = 1, resgoodslog = 1,goodsdata = []
				if (goodslog.length > 0) {
					for (var i = goodslog.length - 1; i >= 0; i--) {
						let goods = await this.model('or_shop_goods').db(guestModel.db()).where({goodsid: goodslog[i].goodsid, shopid: this.shop_userinfo.departmentid}).find()
						goods.nums -= Number(goodslog[i].nums)
						goodsdata.push(goods)
					}
					resgoods = await this.model('or_shop_goods').db(guestModel.db()).updateMany(goodsdata)
					resgoodslog = await this.model('or_shop_goodslog').db(guestModel.db()).where({ordertype: 'LSD', orderid: id}).delete()
				}

				// 如果有暂存的话，删除暂存的商品
				let reszancun = await this.model('or_shop_guest_temp_reserve').db(guestModel.db()).where({orderid: id, shopid: this.shop_userinfo.departmentid}).delete()

				// 如果有卡项消费，删除消费日志，返还次卡次数和金额
				let guestcardlog = await this.model('or_shop_guestcardlog').db(guestModel.db()).where({orderid: id, ordertype: 'LSD'}).select()
				let resguestcard = 1,resguestcardlog = 1
				if (guestcardlog.length > 0) {
					let guestcardsubjectdata = []
					for (var i = guestcardlog.length - 1; i >= 0; i--) {
						let guestcardsubject = await this.model('or_shop_guestcardsubject').db(guestModel.db()).where({id: guestcardlog[i].guestcardinfoid}).find()
						guestcardsubject.nownum -= Number(guestcardlog[i].num)
						guestcardsubject.amount -= Number(guestcardlog[i].amount)
						guestcardsubjectdata.push(guestcardsubject)
					}
					resguestcard = await this.model('or_shop_guestcardsubject').db(guestModel.db()).updateMany(guestcardsubjectdata)
					resguestcardlog = await this.model('or_shop_guestcardlog').db(guestModel.db()).where({orderid: id, ordertype: 'LSD'}).delete()
				}


				// 因为暂存目前没有日志表，所以只能从订单表中取
				let restemp = 1, tempdata = []
				for (var i = olist.length - 1; i >= 0; i--) {
					if (olist[i].consumetype == 3) {
						let temp = await this.model('or_shop_guest_temp_reserve').db(guestModel.db()).where({id:olist[i].tempid}).find()
						temp.nownum += Number(olist[i].num)
						tempdata.push(temp)
					}
				}

				if (tempdata.length > 0) {
					restemp = await this.model('or_shop_guest_temp_reserve').db(guestModel.db()).updateMany(tempdata)
				}	
				
				// 更改订单状态为1表示订单已结账
				resorder =  await guestModel.where({id: id}).update(orderdata)

				//完善预约（保留）
				//获取今天时间戳范围
				let date = new Date();
				let btoday = Math.round(new Date(date.getFullYear(),date.getMonth(),date.getDate(),0,0,0).getTime()/1000);
				let etoday = btoday+86400;
				let resyuyue = await this.model('bespeak').db(guestModel.db()).execute('UPDATE `think_bespeak` SET `type`=1,`arrivetime`=0 WHERE  `guestid` = '+oinfo.guestid+' and bespeaktime >= '+btoday+' and bespeaktime < '+etoday)
				
				/*console.log(resyeji)
				console.log(resxianjin)
				console.log(resorder)
				console.log(resreduce)
				console.log(resdelbalancelog)
				console.log(resbalance)
				console.log(resaccount)
				console.log(resaccountlog)
				console.log(resgoods)
				console.log(resgoodslog)
				console.log(reszancun)
				console.log(resguestcard)
				console.log(resguestcardlog)
				console.log(restemp)
				console.log(resyuyue)*/

				if (resyeji !== false && resxianjin !== false && resorder && resreduce !== false && resdelbalancelog && resbalance && resaccount && resaccountlog && resgoods && resgoodslog && resguestcard && resguestcardlog && reszancun !== false && restemp) {
					await guestModel.commit();
					return this.success({data:200, info:'反结账成功'});
				} else {
					await guestModel.rollback();
					return this.fail('反结账失败');
				}

			}catch(e){
				
				await guestModel.rollback();
				console.log(e)
				return this.fail('反结账失败');
			}
		})
	}
	// 计算订单的现金提成，卡耗提成，手工提成
	async getjisuantichengAction () {
		let id = this.post('id')
		// 列出订单信息
		let  orderlist = await this.model('or_shop_orderinfo').where({orderid: id}).select()
		let ax = 0, ak = 0 // 总现金业绩，总卡耗业绩
		let xt = 0, kt = 0, st = 0 // 总现金卡耗手工提成
		for (var i = orderlist.length - 1; i >= 0; i--) {
			let x = 0, k = 0
			if (orderlist[i].consumetype == 1) {
				// 普通的产品消费
				x = orderlist[i].usemoney
				k = orderlist[i].usebalance + Number(orderlist[i].usegiftbalance)
				if (orderlist[i].type == 1) {
					// 取商品
					let goods = await this.model('or_shop_goods')
					.where({goodsid: orderlist[i].typeid, shopid: this.shop_userinfo.departmentid})
					.find()
					// 取现金业绩和卡耗业绩
					orderlist[i].xianjinticheng = goods.tdtype == 1 ? x * goods.percent : x / (x + k) * orderlist[i].num * goods.fixed
					orderlist[i].kahaoticheng = goods.khtdtype == 1 ? k * goods.khpercent : k / (x + k) * orderlist[i].num * goods.khfixed			
				}
				if (orderlist[i].type == 2) {
					let subject = await this.model('or_shop_subject').where({subjectid: orderlist[i].typeid, shopid: this.shop_userinfo.departmentid}).find()
					orderlist[i].xianjinticheng = subject.xstdtype == 1 ? x * subject.xspercent : x / (x + k) * orderlist[i].num * subject.xsfixed

					orderlist[i].kahaoticheng = subject.khtdtype == 1 ? k * subject.khpercent : k / (x + k) * orderlist[i].num * subject.khfixed
					orderlist[i].shougongticheng = subject.sgtdtype == 1 ? orderlist[i].amount * subject.sgpercent : orderlist[i].num * subject.sgfixed
				}

			}
			if (orderlist[i].consumetype == 2) {
				let subject = await this.model('or_shop_subject').where({subjectid: orderlist[i].typeid, shopid: this.shop_userinfo.departmentid}).find()
				x = orderlist[i].usemoney
				k = orderlist[i].usebalance + Number(orderlist[i].usegiftbalance) + Number(orderlist[i].usecard)
				orderlist[i].xianjinticheng = subject.xstdtype == 1 ? x * subject.xspercent : x / (x + k) * orderlist[i].num * subject.xsfixed
				orderlist[i].kahaoticheng = subject.khtdtype == 1 ? k * subject.khpercent : k / (x + k) * orderlist[i].num * subject.khfixed
				orderlist[i].shougongticheng = subject.sgtdtype == 1 ? orderlist[i].amount * subject.sgpercent : orderlist[i].num * subject.sgfixed
			}

			if (orderlist[i].consumetype == 3) {
				if (orderlist[i].type == 2) {
					let subject = await this.model('or_shop_subject').where({subjectid: orderlist[i].typeid, shopid: this.shop_userinfo.departmentid}).find()
					orderlist[i].xianjinticheng = 0
					orderlist[i].kahaoticheng = 0
					orderlist[i].shougongticheng = subject.sgtdtype == 1 ? orderlist[i].amount * subject.sgpercent : orderlist[i].num * subject.sgfixed
				}
			}
			orderlist[i].xianjinticheng = orderlist[i].xianjinticheng ? orderlist[i].xianjinticheng.toFixed(2) : 0
			orderlist[i].kahaoticheng = orderlist[i].kahaoticheng ? orderlist[i].kahaoticheng.toFixed(2) : 0 
			orderlist[i].shougongticheng = orderlist[i].shougongticheng ? orderlist[i].shougongticheng.toFixed(2) : 0
			ax += Number(x)
			ak += Number(k)
			
			xt += Number(orderlist[i].xianjinticheng)
			kt += Number(orderlist[i].kahaoticheng)
			st += Number(orderlist[i].shougongticheng)
		}
		let fenpeilist = await this.model('or_shop_yejiticheng')
		.alias('y')
		.field('y.*, u.name')
		.join('left join `think_or_app_user` u on y.userid = u.id')
		.where({'y.ordertype': 'LSD', 'y.orderid': id})
		.select()

		let order = await this.model('or_shop_order').where({id: id}).find()
		if (fenpeilist.length > 0 && order.status != 2) {
			for (var i = fenpeilist.length - 1; i >= 0; i--) {
				let x = ((fenpeilist[i].xianjinyeji / ax) * xt).toFixed(2)
				let k = ((fenpeilist[i].kahaoyeji / ak) * kt).toFixed(2)
				x = x == 'NaN' ? 0 : x
				k = k == 'NaN' ? 0 : k
				fenpeilist[i].xianjinticheng = x || 0 
				fenpeilist[i].kahaoticheng = k || 0
			}
		}
		let data = {
			orderlist: orderlist,
			fenpeilist: fenpeilist
		}
		return this.json(data)
	}
}